package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.dto.MemberUserDto;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/user")
@Validated
public class AdminUserController {
    private final Log logger = LogFactory.getLog(AdminUserController.class);

    @Autowired
    private LitemallUserService userService;

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String username, String mobile,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallUser> userList = userService.querySelective(username, mobile, page, limit, sort, order);
        return ResponseUtil.okList(userList);
    }

    //todo  根据会员id手工开启vip
    // 0、根据id查询相应的会员信息
    // 0.0 vip验证
    // 1. 修改会员表的状态
    // 2. 添加vip表信息

    /**
     * 普通会员手动改为vip
     *
     * @param userId
     * @param memberRoleId
     * @return
     */
    @PostMapping("/makeUserToVIP")
    public Object makeOrdinaryUserToUserMember(@RequestBody MemberUserDto dto) {
        Integer userId = dto.getUserId();
        Integer memberRoleId = dto.getMemberRuleId();
        String phoneNumber = dto.getPhoneNumber();

        Map<String, String> map = userService.makeOrdinaryUserToUserMember(userId, memberRoleId, phoneNumber);
        if ("200".equals(map.get("error"))) {
            return ResponseUtil.ok();
        } else {
            return ResponseUtil.fail(Integer.parseInt(map.get("error")), map.get("errorDesc"));
        }
    }
}
